/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xw.framework.vo.ShiroUser;
import com.xw.framework.vo.UserSessionInfo;

/**
 * The Class ShiroSecurityUtil.
 *
 * @author Xi Wei
 */
public class ShiroSecurityUtil {

	/**
	 * Gets the login id.
	 *
	 * @return the login id
	 */
	public static Long getLoginId() {
		try {
			if (SecurityUtils.getSubject() != null && SecurityUtils.getSubject().getPrincipal() != null) {
				return ((ShiroUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal()).getId();
			}
		} catch (Exception e) {
			// e.printStackTrace();
			return Long.valueOf(1);
		}
		return Long.valueOf(1);
	}

	/**
	 * Gets the system id.
	 *
	 * @return the system id
	 */
	public static Long getSystemId() {
		try {
			if (SecurityUtils.getSubject() != null && SecurityUtils.getSubject().getPrincipal() != null) {
				return ((ShiroUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal()).getSystemId();
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	/**
	 * Gets the user session info.
	 *
	 * @return the user session info
	 */
	public static UserSessionInfo getUserSessionInfo() {
		UserSessionInfo usi = null;
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			usi = (UserSessionInfo) request.getSession().getAttribute(UserSessionInfo.USER_SESSION_INFO_KEY);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		return usi;
	}
}
